package com.sxkiler.demo.seata.service;

import com.sxkiler.demo.seata.dao.TCCAccountDao;
import com.sxkiler.demo.seata.service.tcc.TCCAccountService;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@org.apache.dubbo.config.annotation.Service
@Service
public class TCCAccountServiceImpl implements TCCAccountService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private TCCAccountDao accountDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean accountTry(BusinessActionContext actionContext, Long userId, Integer price) {
        String xId = actionContext.getXid();
        long branchId = actionContext.getBranchId();
        logger.info("[accountTry]: 当前 XID:{}, branchId:{}, 用户:{}， 金额:{}", xId, branchId, userId, price);
        int flag = accountDao.accountTry(userId, price);
        if(flag == 0){
            throw new RuntimeException("账户服务 Try 阶段失败.");
        }
        logger.info("[accountTry]: 冻结 {} 余额成功", price);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean accountConfirm(BusinessActionContext actionContext) {
        String xId = actionContext.getXid();
        long branchId = actionContext.getBranchId();
        Integer userId = ((Integer) actionContext.getActionContext("userId"));
        Integer price = ((Integer) actionContext.getActionContext("price"));
        logger.info("[accountConfirm]: 当前 XID:{}, branchId:{}, 用户:{}， 金额:{}", xId, branchId, userId, price);

        int flag = accountDao.accountConfirm(userId.longValue(), price);
        if(flag == 0){
            throw new RuntimeException("账户服务 Confirm 阶段失败.");
        }
        logger.info("[accountConfirm]: 扣减 {} 余额成功", price);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean accountCancel(BusinessActionContext actionContext) {
        String xId = actionContext.getXid();
        long branchId = actionContext.getBranchId();
        Integer userId = ((Integer) actionContext.getActionContext("userId"));
        Integer price = ((Integer) actionContext.getActionContext("price"));
        logger.info("[accountCancel]: 当前 XID:{}, branchId:{}, 用户:{}， 金额:{}", xId, branchId, userId, price);

        int flag = accountDao.accountCancel(userId.longValue(), price);
        if(flag == 0){
            throw new RuntimeException("账户服务 Cancel 阶段失败.");
        }

        return true;
    }
}
